import React, { useEffect, useRef, useState } from 'react';
import { customAlphabet } from 'nanoid';
import { Modal, Divider, Select } from 'antd';
import styled from '@emotion/styled';
import MessageList, { IMessage } from '@/components/KnowledgeBase/MessageList';
import ChatInput from '@/components/KnowledgeBase/ChatInput';
import { getKnowledgeBaseAsk, getKnowledgeBaseCategoryOptions, getQaKnowledgeBaseOptions, getQaKnowledgeBaseAsk } from '@/api/index';
import { useBusiness } from '@/views/Context/BusinessContext';
import AgentService from '@/modules/Agent';
import { IBusinessName } from '../Context/BusinessContext';
import Message from '@/utils/message';
import { useTranslation } from 'react-i18next';
import SelectContent from '../SendCommand/SelectContent';
import Tabs from '../SendCommand/Tabs';
import { appendToken, removeToken } from '@/utils/index';

interface IPDFResource {
	name: string;
	url: string;
	size: number;
	suffix: string;
}

interface ChatPageProp {
	visible: boolean;
	close: () => void;
	showCustomerRoleOrName?: boolean;
}

const MessageListContainer = styled.div`
	flex: 1;
	overflow-y: auto;
	padding: 0;
	background-color: #fff;
`;

interface customerNameProps {
	name: string | null;
	active: boolean;
	clientId: string;
	id: string;
}

interface customerRoleProps {
	name: string | null;
	active: boolean;
}

const TitleContianer = styled.p`
	font-size: 13px;
	font-weight: 400;
	color: #202020;
	margin: 0;
`;

const SearchTitle = styled.div`
	display: flex;
	justify-content: space-between;
	align-items: center;
`;

const SearchBar = styled.div`
	display: flex;
	align-items: center;
	width: 100%;
	gap: 20px;
	margin-bottom: 8px;
`;

const ChatPage: React.FC<ChatPageProp> = props => {
	const { t } = useTranslation();
	const { close, visible, showCustomerRoleOrName } = props;
	const [messageList, setMessageList] = useState<IMessage[]>([]);
	const messageListRef = useRef<HTMLDivElement>(null);
	const { sendBusiness } = useBusiness();
	const [tabTypes, setTabTypes] = useState<string>('customerNameTabs');
	const [customerName, setCustomerName] = useState<customerNameProps[]>([]);
	const [customerRole, setCustomerRole] = useState<customerRoleProps[]>([]);
	const [selectErrorMessage, setSelectErrorMessage] = useState<string>('');
	const [selectErrorMessageRole, setSelectErrorMessageRole] = useState<string>('');
	const [group, setGroup] = useState([]);
	const [qaList, setQaList] = useState([]);
	const [selectedQa, setSelectedQa] = useState<string | undefined>(undefined);
	const [categoryList, setCategoryList] = useState([]);
	const [selectedCategory, setSelectedCategory] = useState<string | undefined>(undefined);

	const GroupAll = { value: 'all', label: '全部问题' };
	const [curCategory, setCurCategory] = useState(GroupAll.value);

	useEffect(() => {
		if (visible) {
			getCustomerData();
			initGetKnowledgeBaseCategoryOptions();
		} else {
			setTabTypes('customerNameTabs');
		}
	}, []);

	const getCategoryList = (id: any) => {
		getKnowledgeBaseCategoryOptions(id)
			.then(resp => {
				console.log('getCategoryList', resp);
				const { data } = resp.data;
				let category = filterCategoryList(data);
				category.unshift(GroupAll);
				setCategoryList(category);
			})
			.catch(err => {
				console.error('getKnowledgeBaseCategoryOptions error ', err);
			});
	};

	const initGetKnowledgeBaseCategoryOptions = () => {
		getQaKnowledgeBaseOptions()
			.then(resp => {
				const { data } = resp.data;
				setQaList(data);
			})
			.catch(err => {
				console.error('getQaKnowledgeBaseOptions error ', err);
			});
	};

	// 过滤分类的第一级
	const filterCategoryList = (data: any) => {
		return data
			? data.map((item: any) => {
					return {
						value: item.id,
						label: item.name
					};
			  })
			: [];
	};

	// 过滤答案
	const filterAnswerList = (data: any) => {
		const getUrl = (url: string) => {
			return appendToken(url);
		};
		return data.map((item: any) => {
			const { id, answer, name, type, fileName } = item;
			return {
				id,
				text: type === 'text' ? answer : getUrl(answer?.replace('http://', 'https://')),
				from: 'robot',
				question: name,
				type,
				fileName
			};
		});
	};

	const handleSearch = (message: string) => {
		if (!selectedQa) return;
		getQaKnowledgeBaseAsk(message, selectedQa, selectedCategory || 'all')
			.then(resp => {
				const { data } = resp.data;
				console.log('getQaKnowledgeBaseAsk data ', data);
				if (data && data.data && data.data.length > 0) {
					let robotMessages = filterAnswerList(data.data);
					setMessageList(robotMessages);
				} else {
					const nanoid = customAlphabet('1234567890abcdef', 10);
					const id = nanoid();
					const noAnswerMessage: IMessage = {
						id: id + '1',
						text: '没有找到相关问题',
						from: 'robot',
						noanswer: true,
						question: '',
						type: 'text',
						fileName: ''
					};
					setMessageList([noAnswerMessage] as any);
				}
			})
			.catch(err => {
				console.error('getKnowledgeBaseAsk error ', err);
			})
			.finally(() => {
				if (messageListRef.current) {
					messageListRef.current.scrollTop = messageListRef.current.scrollHeight;
				}
			});
	};

	const handleSelect = (question: string) => {
		handleSearch(question);
	};

	const handleSend = async (message: IMessage) => {
		if (!AgentService.sessionId) {
			Message.warning(t('no-calls'));
			return;
		}
		if (verification()) return;
		console.log('handleSend ', message);
		const { id, text, type = '', fileName = '', question } = message;
		try {
			let recievers = getSendData();
			// if (type === 'video') {
			// 	// sendBusiness(IBusinessName.SEND_VIDEO_LINK, text, data);
			// } else if (type === 'pdf') {
			// 	const pdfResource: IPDFResource = {
			// 		name: fileName,
			// 		url: text,
			// 		size: 1000,
			// 		suffix: 'pdf'
			// 	};
			// 	// sendBusiness(IBusinessName.SEND_PDF, pdfResource, data);
			// } else {
			// 	// 构造链接 https://localhost:5173/knowledge/answer?id=12
			// 	const link = `/knowledge/answer?id=${id}`;
			// 	// sendBusiness(IBusinessName.SEND_LINK, link, data);
			// }
			const data = {
				subType: type,
				name: fileName,
				url: ['video', 'pdf', 'image'].includes(type) ? removeToken(text) : '',
				data: ['video', 'pdf', 'image'].includes(type) ? {} : { content: `<p>${text}</p>` },
				question: question
			};
			await sendBusiness(IBusinessName.SEND_KNOWLEDGE_BASE, data, recievers);
			close();
		} catch (error) {
			console.error('handleSend error ', error);
			Message.warning(t('send-knowledge-base-failed'));
		}
	};

	const getCustomerData = () => {
		let customerMembers = AgentService.getCustomerMediaStream();
		console.log(customerMembers, ':customerMembers');
		let getCustomerName: customerNameProps[] = [];
		let getCustomerRole: customerRoleProps[] = [];
		getCustomerName = customerMembers.map(item => {
			return {
				name: item.userName,
				active: true,
				clientId: item.clientId,
				id: item.id!.toString()
			};
		});
		getCustomerRole = customerMembers.map(item => {
			return {
				name: item.customerRole || '',
				active: true
			};
		});
		getCustomerRole = getCustomerRole.reduce((all: any[], next: { [x: string]: any }) => (all.some((item: { [x: string]: any }) => item['name'] == next['name']) ? all : [...all, next]), []);
		console.log(getCustomerName, ':getCustomerName', getCustomerRole, ':getCustomerRole');
		setCustomerName(getCustomerName);
		setCustomerRole(getCustomerRole);
	};

	const selectNameOrRole = (data: any) => {
		let newCustomerName: any = [];
		if (data.clientId) {
			newCustomerName = customerName.map(item => {
				return {
					name: item.name,
					active: item.name === data.name ? !item.active : item.active,
					clientId: item.clientId
				};
			});
			setCustomerName(newCustomerName);
		} else {
			newCustomerName = customerRole.map(item => {
				return {
					name: item.name,
					active: item.name === data.name ? !item.active : item.active
				};
			});
			setCustomerRole(newCustomerName);
		}
	};

	const getSendData = () => {
		let data: string[] = [];
		let customerMembers = AgentService.getCustomerMediaStream();
		if (showCustomerRoleOrName) {
			if (tabTypes === 'customerNameTabs') {
				customerName.forEach(item => {
					if (item.active) {
						data.push(item.clientId);
					}
				});
			} else {
				customerRole.forEach(item => {
					if (item.active) {
						customerMembers.forEach(ele => {
							if (ele.customerRole === item.name) {
								data.push(ele.clientId);
							}
						});
					}
				});
			}
		} else {
			data.push(customerMembers[0].clientId);
		}

		return data;
	};

	const verification = () => {
		let data = getSendData();
		let flag = false;
		if (data.length === 0) {
			if (tabTypes === 'customerNameTabs') {
				setSelectErrorMessage('*' + t('select-client-role-for-push'));
			} else {
				setSelectErrorMessageRole('*' + t('select-client-role-for-push'));
			}
			flag = true;
		} else {
			setSelectErrorMessage('');
			setSelectErrorMessageRole('');
		}
		return flag;
	};

	const handleGroupChange = (value: string) => {
		console.log(`selected ${value}`);
		setCurCategory(value);
	};

	const handleQaChange = (value: string) => {
		setSelectedQa(value);
		setSelectedCategory(undefined);
		getCategoryList(value);
	};

	const handleCategoryChange = (value: string) => {
		setSelectedCategory(value);
	};

	return (
		<Modal title={t('knowledgebase')} open={visible} centered={true} closable={true} width={900} footer={[]} onCancel={close}>
			<div>
				<SearchTitle>
					<SearchBar>
						<Select
							style={{ width: 200 }}
							options={(qaList || []).map((item: any) => ({ value: item.id, label: item.name }))}
							value={selectedQa}
							onChange={handleQaChange}
							placeholder="请选择知识库"
						/>
						<Select style={{ width: 200 }} options={categoryList} value={selectedCategory} onChange={handleCategoryChange} placeholder="请选择分类" disabled={!selectedQa} />
						<div style={{ flex: 1, minWidth: 0 }}>
							<ChatInput onSearch={handleSearch} />
						</div>
					</SearchBar>
				</SearchTitle>

				<MessageListContainer ref={messageListRef}>
					<MessageList messageList={messageList as any} onSelect={handleSelect} onSend={handleSend} />
				</MessageListContainer>
			</div>
			{showCustomerRoleOrName ? (
				<>
					<Divider></Divider>
					<TitleContianer>{t('select-client-for-push')}</TitleContianer>
					<Tabs
						tabsType={tabTypes}
						onClick={type => {
							type && setTabTypes(type);
						}}
					/>
					<SelectContent
						tabTypes={tabTypes}
						array={tabTypes === 'customerNameTabs' ? customerName : customerRole}
						onClick={selectNameOrRole}
						selectErrorMessage={selectErrorMessage}
						selectErrorMessageRole={selectErrorMessageRole}
					/>
				</>
			) : (
				''
			)}
		</Modal>
	);
};

export default ChatPage;
